package com.suixun.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authority.dao.AuthUserDataDao;
import com.authority.utils.CommonUtils;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.SchooltimesettingMapper;
import com.suixun.dao.SchooltypeMapper;
import com.suixun.dao.devicemanage.DeviceInitServiceDAO;
import com.suixun.dao.devicemanage.DeviceServiceDAO;
import com.suixun.dao.schoolmanage.SchoolServiceDAO;
import com.suixun.dao.studentmanage.StudentManageDAO;
import com.suixun.document.XmlDocument;
import com.suixun.entity.RegionInfo;
import com.suixun.entity.School;
import com.suixun.entity.SchoolDiscountDO;
import com.suixun.entity.Schoolinfo;
import com.suixun.entity.Schooltimesetting;
import com.suixun.entity.Schooltype;
import com.suixun.entity.SchooltypeExample;
import com.suixun.entity.form.ParamForm;
import com.suixun.entity.jxt.JxtSchool;
import com.suixun.entity.page.PageModel;
import com.suixun.exception.OpServiceException;
import com.suixun.jxt.service.JxtService;
import com.suixun.service.SchoolService;
import com.suixun.service.SysOrgnizationService;
import com.suixun.service.cache.CacheService;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.StringUtil;
import com.suixun.vo.SchoolDiscountVO;
import com.suixun.vo.SchoolVO;

import net.sf.json.JSONObject;

@Service
public class SchoolServiceImpl implements SchoolService {

	@Resource
	private SchoolServiceDAO schooldao;
	@Resource
	private CacheService cacheService;
	@Resource
	private DeviceServiceDAO deviceServiceDAO;
	@Resource
	private StudentManageDAO studentManageDAO;
	@Resource
	private DeviceInitServiceDAO deviceInitServiceDAO;
	@Resource
	private SchooltimesettingMapper schooltimesettingMapper;
	@Resource
	private XmlDocument<RegionInfo,List<RegionInfo>> xmlDocument;
	@Resource
	private AuthUserDataDao authUserDataDao;
	@Resource
	private SchooltypeMapper schooltypeMapper;
	@Resource
	private JxtService jxtService;
	@Resource
	private SysOrgnizationService sysOrgnizationService;
	@Resource
	private SchoolinfoMapper schoolinfoMapper;

	// 查询某个学校明细
	@Override
	public School querySchoolByName(ParamForm paramForm) {
		if (StringUtil.isBlank(paramForm.getSchoolname()))
			return null;
		School school = schooldao.querySchoolByName(paramForm);
		return school;
	}

	// 查询某个学校明细
	@Override
	public School querySchoolByID(ParamForm paramForm) {
		if (StringUtil.isBlank(paramForm.getSchoolid()))
			return null;
		School school = schooldao.querySchoolByID(paramForm);
		return school;
	}

	// 查询学校里面的学生数量
	@Override
	public int querySchoolStudentCounts(ParamForm paramForm) {
		if (StringUtil.isBlank(paramForm.getSchoolid()))
			return -1;
		return schooldao.querySchoolStudentCounts(paramForm);
	}

	
	// 查询学校列表
	@Override
	public List<School> querySchoollist(ParamForm paramForm) {
		if (!StringUtil.isBlank(paramForm.getSchoolname()))
			paramForm.setSchoolname(paramForm.getSchoolname());
		List<School> devicelist = schooldao.querySchoollist(paramForm);
		if (paramForm.getProvince() != null) {
			Integer studentCounts = null;
			for (School school : devicelist) {
				paramForm.setSchoolid(String.valueOf(school.getId()));
				studentCounts = schooldao.querySchoolStudentCounts(paramForm);
				if (studentCounts != null) {
					school.setStudentCount(studentCounts);
				}
			}
		}
		return devicelist;
	}

	// 分页查询学校列表
	@Override
	public PageModel<SchoolVO> querySchoollistPage(ParamForm paramForm) throws Exception {

		PageModel<SchoolVO> pageModel = new PageModel<SchoolVO>();
		if (StringUtil.isNotEmpty(paramForm.getSchoolname())) {
			pageModel.getQueryparam().put("schoolname", paramForm.getSchoolname());
		}

		if (StringUtil.isNotEmpty(paramForm.getPagecount())) {
			pageModel.setPagesize(Integer.parseInt(paramForm.getPagecount()));
		}
		Integer totleRows = schooldao.countRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
			pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
		}
		List<School> schoolList = schooldao.querySchoollistPage(pageModel);
		for (int i = 0; i < schoolList.size(); i++) {
			School school = schoolList.get(i);
			StringBuffer time = new StringBuffer();
			List<Schooltimesetting> timeList = schooldao.querySchooltimesettings(school.getId());
			if (timeList.size() > 0) {
				StringBuilder timeSettingids = new StringBuilder();
				for (int j = 0; j < timeList.size(); j++) {
					Schooltimesetting timssetting = timeList.get(j);
					time.append(DateUtil.formatDateToString(timssetting.getStarttime(),"HH:mm")).append("-")
					.append(DateUtil.formatDateToString(timssetting.getEndtime(),"HH:mm")).append(" ");
					timeSettingids.append(",").append(timssetting.getId());
				}
				school.setTimeSettingid(timeSettingids.substring(1));
			}
			school.setShowtimesetting(time.toString());
			school.setSchooltimesetting(null);
		}
		List<SchoolVO> schoolVOList = CommonUtils.dbToVo2(schoolList, SchoolVO.class);
		/*if (schoolVOList.size() > 0) {
			for (int i = 0 ; i < schoolVOList.size() ; i ++) {
				if (schoolList.get(i).getDiscountprice() != null) {
					schoolVOList.get(i).setPrice(schoolList.get(i).getDiscountprice());
				}
			}
		}*/
		pageModel.setQueryresult(schoolVOList);
		return pageModel;
	}
	
    @Override
    public PageModel<SchoolVO> querySchoollistPage(ParamForm paramForm, Integer type) throws Exception {

        PageModel<SchoolVO> pageModel = new PageModel<SchoolVO>();
        if (StringUtil.isNotEmpty(paramForm.getSchoolname())) {
            pageModel.getQueryparam().put("schoolname", paramForm.getSchoolname());
        }

        if (StringUtil.isNotEmpty(paramForm.getPagecount())) {
            pageModel.setPagesize(Integer.parseInt(paramForm.getPagecount()));
        }
        
        Integer totleRows = schooldao.countRowsByType(pageModel, type);
        pageModel.setTotlepage(totleRows);
        if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
            pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
        }
        List<School> schoolList = schooldao.querySchoollistPageByType(pageModel, type);
        for (int i = 0; i < schoolList.size(); i++) {
            School school = schoolList.get(i);
            StringBuffer time = new StringBuffer();
            List<Schooltimesetting> timeList = schooldao.querySchooltimesettings(school.getId());
            if (timeList.size() > 0) {
                StringBuilder timeSettingids = new StringBuilder();
                for (int j = 0; j < timeList.size(); j++) {
                    Schooltimesetting timssetting = timeList.get(j);
                    time.append(DateUtil.formatDateToString(timssetting.getStarttime(),"HH:mm")).append("-")
                    .append(DateUtil.formatDateToString(timssetting.getEndtime(),"HH:mm")).append(" ");
                    timeSettingids.append(",").append(timssetting.getId());
                }
                school.setTimeSettingid(timeSettingids.substring(1));
            }
            school.setShowtimesetting(time.toString());
            school.setSchooltimesetting(null);
        }
        List<SchoolVO> schoolVOList = CommonUtils.dbToVo2(schoolList, SchoolVO.class);
        /*if (schoolVOList.size() > 0) {
            for (int i = 0 ; i < schoolVOList.size() ; i ++) {
                if (schoolList.get(i).getDiscountprice() != null) {
                    schoolVOList.get(i).setPrice(schoolList.get(i).getDiscountprice());
                }
            }
        }*/
        pageModel.setQueryresult(schoolVOList);
        return pageModel;
    }

	 
	// 查询行政区域
	@Override
	public List<RegionInfo> queryRegion(RegionInfo paramForm) throws DocumentException {
		return xmlDocument.parserXml("province_data.xml",paramForm);
	}

	// 新增学校
	@Override
	@Transactional
	public String addSchool(SchoolVO schoolVO, long operatorid,String schooltype) {
		JSONObject orgnization = null;
		if(StringUtils.isEmpty(schooltype)) {
			orgnization = synSchoolWithJxt(schoolVO);
		}
		Schoolinfo schoolinfo = new Schoolinfo();
		schoolinfo.setSchoolname(schoolVO.getSchoolname());
		schoolinfo.setAddress(schoolVO.getAddress());
		schoolinfo.setDis(schoolVO.getDis() == null ? "" : schoolVO.getDis());
		schoolinfo.setPhone(schoolVO.getPhone());
		schoolinfo.setYijiaoid(schoolVO.getYijiaoid());
		schoolinfo.setProvince(schoolVO.getProvince());
		schoolinfo.setCity(schoolVO.getCity());
		schoolinfo.setTown(schoolVO.getTown());
		if(orgnization != null) {
			schoolinfo.setJxtId(orgnization.getString("uuid"));
		}
		
		schoolinfoMapper.insert(schoolinfo);
		//添加考勤区间
		addSchooltimesetting(schoolinfo.getId(), schoolVO.getShowtimesetting(), operatorid);
		
		//和教育学校设置
		try {
			if(StringUtil.isNotEmpty(schooltype)&& StringUtils.isNumeric(schooltype)/*schooltype.equals("1")*/){
				SchooltypeExample schooltypeExample = new SchooltypeExample();
				schooltypeExample.createCriteria().andSchoolidEqualTo(schoolinfo.getId()).andTypeEqualTo(Integer.parseInt(schooltype));
				List<Schooltype> schooltypes = schooltypeMapper.selectByExample(schooltypeExample);
				if(schooltypes == null || schooltypes.size() == 0){
					Schooltype schooltype1 = new Schooltype();
					schooltype1.setSchoolid(schoolinfo.getId());
					schooltype1.setSchoolname(schoolVO.getSchoolname());
					schooltype1.setType(Integer.parseInt(schooltype));
					schooltypeMapper.insert(schooltype1);
				}
			}
		}catch (NumberFormatException e) {
			return "学校类型非有校数字";
		} catch (Exception e) {
			return "设置和教育学校失败";
		}
		
		return Constant.SUCCESS;
	}
	
	/**
	 * <p>Title: addSchooltimesetting</p>
	 * <p> 功能描述: 新增考勤区间</p>
	 * @param schoolid
	 * @param schooltimesetting
	 * @param operatorid
	 * @return
	 */
	public int addSchooltimesetting(Integer schoolid, String schooltimesetting, long operatorid) {
		if (!StringUtil.isBlank(schooltimesetting)) {
			String[] timeList = schooltimesetting.split(",");
			List<Schooltimesetting> list = new LinkedList<Schooltimesetting>();
			for (int i = 0; i < timeList.length; i++) {
				String timeTemp = timeList[i];
				if (StringUtil.isBlank(timeTemp) || timeTemp.indexOf("-") < 0)
					continue;
				String[] timeValue = timeTemp.split("-");
				Schooltimesetting time = new Schooltimesetting();
				time.setSchoolid(schoolid);
				time.setStarttime(DateUtil.formatStringToTime(timeValue[0], ""));
				time.setEndtime(DateUtil.formatStringToTime(timeValue[1], ""));
				
				time.setIndexnum(i + 1);
				time.setSellerid(new Integer(operatorid + ""));
				time.setType((byte) 1);
				list.add(time);
				schooldao.addSchooltimesetting(time);
			}
		}
		return 0;
	}
	/**
	 * <p>Title: addSchoolDiscount</p>
	 * <p> 功能描述:新增促销 </p>
	 * @param schoolVO
	 * @return
	 */
	public int addSchoolDiscount(SchoolVO schoolVO) {
		if (schoolVO.getPrice() != null) {
			if (StringUtil.isEmpty(schoolVO.getStarttime()) || StringUtil.isEmpty(schoolVO.getEndtime())) {
				return -1;
			}
			int checkTime = DateUtil.formatStringToTime(schoolVO.getStarttime(), "yyyy-MM-dd HH:mm:ss")
									.compareTo(DateUtil.formatStringToTime(schoolVO.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
			if (checkTime != -1) {
				return -2;
			}
			Map<String,Object> map = new HashMap<>();
			map.put("devicetype", 2);
			map.put("discountprice", schoolVO.getPrice());
			map.put("starttime", schoolVO.getStarttime());
			map.put("endtime", schoolVO.getEndtime());
			map.put("schoolid", schoolVO.getId());
			//查询促销是否存在
			SchoolDiscountDO schoolDiscountDO = schooldao.querySchoolDiscount(schoolVO.getId());
			if (schoolDiscountDO != null) {
				return schooldao.updateSchoolDiscount(map);
			}
			return schooldao.addSchoolDiscount(map);
		}
		return 0;
	}
	
	// 修改学校
	@Override
	@Transactional
	public String modifySchool(SchoolVO schoolVO, long operatorid,String schooltype) {
		if (schoolVO == null || schoolVO.getId() == null) {
			return Constant.EMPTY;
		}
		String checkRegionIsNull = 
				checkRegionIsNull(schoolVO.getProvince(),schoolVO.getCity(),schoolVO.getTown());
		if (!Constant.TRUE.equals(checkRegionIsNull)) {
			return checkRegionIsNull;
		}
		
		// 修改sys_orgnization表数据
		if(StringUtils.isNotBlank(schoolVO.getSchoolname())) {
			//查询学校
			Schoolinfo school = schoolinfoMapper.selectByPrimaryKey(schoolVO.getId());
			if(school == null) {
				return "学校不存在";
			}else if (StringUtils.isBlank(school.getJxtId())) {
				return "学校数据有误，请联系管理员";
			}
			// 修改
			sysOrgnizationService.update(school.getJxtId(), schoolVO.getSchoolname(), null, null);
		}
		
		//查询原学校名称
		ParamForm param = new ParamForm();
		param.setSchoolid(String.valueOf(schoolVO.getId()));
		School school = schooldao.querySchoolByID(param);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", schoolVO.getId());
		map.put("schoolname", schoolVO.getSchoolname());
		map.put("address", schoolVO.getAddress());
		map.put("dis", schoolVO.getDis());
		map.put("phone", schoolVO.getPhone());
		map.put("yijiaoid", schoolVO.getYijiaoid());
		map.put("province", schoolVO.getProvince());
		map.put("city", schoolVO.getCity());
		map.put("town", schoolVO.getTown());
		// 先更新学校信息表
		int result = schooldao.updateSchool(map);

		// 新增新的考勤配置
		int res = updateSchooltimesetting(schoolVO);
		if (res == -1) {
			return "考勤信息有误";
		}
		/*//修改促销
		int isUpdate = updateSchoolDiscount(schoolVO);
		if (isUpdate == -1) {
			return Constant.School.DISCOUNT_TIME_EMPTY;
		}else if (isUpdate == -2) {
			return Constant.School.DISCOUNT_TIME_FALSE;
		}*/
		if (StringUtil.isNotEmpty(schoolVO.getProvince())) {
			updateAuthUserData(schoolVO.getId(),schoolVO.getProvince(),
					schoolVO.getCity(),schoolVO.getTown(),schoolVO.getOperationerid(),schoolVO.getOperatorName());
		}
		//和教育学校设置
		try {
			if(StringUtil.isNotEmpty(schooltype)&& StringUtils.isNumeric(schooltype)/*schooltype.equals("1")*/){
				SchooltypeExample schooltypeExample = new SchooltypeExample();
				schooltypeExample.createCriteria().andSchoolidEqualTo(schoolVO.getId()).andTypeEqualTo(Integer.parseInt(schooltype));
				List<Schooltype> schooltypes = schooltypeMapper.selectByExample(schooltypeExample);
				if(schooltypes == null || schooltypes.size() == 0){
					Schooltype schooltype1 = new Schooltype();
					schooltype1.setSchoolid(schoolVO.getId());
					schooltype1.setSchoolname(schoolVO.getSchoolname());
					schooltype1.setType(Integer.parseInt(schooltype));
					schooltypeMapper.insert(schooltype1);
				}
			}else {
				SchooltypeExample schooltypeExample = new SchooltypeExample();
				schooltypeExample.createCriteria().andSchoolidEqualTo(schoolVO.getId()).andTypeEqualTo(1);
				List<Schooltype> schooltypes = schooltypeMapper.selectByExample(schooltypeExample);
				if(schooltypes != null &&schooltypes.size() > 0){
					schooltypeMapper.deleteByExample(schooltypeExample);
				}
			}
		}catch (NumberFormatException e) {
			return "学校类型非有校数字";
		} catch (Exception e) {
			return "设置和教育学校失败";
		}
		if (result > 0) {
			//修改该学校下的设备
			map.put("schoolname", school.getSchoolname());
			map.put("newSchoolname", schoolVO.getSchoolname());
			deviceServiceDAO.updateSchool(map);
			deviceInitServiceDAO.updateIotDevice(map);
			//修改该学校下的学生
			studentManageDAO.updateSchool(map);
			//清除学校缓存
			cacheService.flushSchoolQuery();
		}
		
		return Constant.SUCCESS;
	}
	
	private String checkRegionIsNull(String province,String city,String town) {
		if (StringUtil.isNotEmpty(province)) {
			if (StringUtil.isEmpty(city) || StringUtil.isEmpty(town)) {
				return "地区不能为空";
			}
		}
		return Constant.TRUE;
	}
	
	/**
	 * <p>Title: updateAuthUserData</p>
	 * <p> 功能描述:修改账号区域权限 </p>
	 * @param schoolid
	 * @param province
	 * @param city
	 * @param town
	 */
	private void updateAuthUserData(Integer schoolid,String province,String city,String town,
			Long operatorId,String operatorName) {
		Map<String,Object> map = new HashMap<>();
		map.put("schoolId", schoolid);
		map.put("province", province);
		map.put("city", city);
		map.put("town", town);
		map.put("operatorId", operatorId);
		map.put("operatorName", operatorName);
		map.put("gmtModified", new Date());
		authUserDataDao.updateRegionBySchoolId(map);
	}
	
	/**
	 * <p>Title: updateSchooltimesetting</p>
	 * <p> 功能描述: 修改考勤区间</p>
	 * @param schoolVO
	 * @param operatorid
	 * @return
	 */
	private int updateSchooltimesetting(SchoolVO schoolVO) {
		String[] timeList = null,updateIndex = null;
		if(StringUtil.isNotEmpty(schoolVO.getShowtimesetting())) {
			timeList = schoolVO.getShowtimesetting().split(",");
		}
		if (StringUtil.isNotEmpty(schoolVO.getTimeSettingid())) {
			updateIndex = schoolVO.getTimeSettingid().split(",");
		}
		if (updateIndex != null) {
			//删除考勤
			if (timeList == null) {
				for (int i = 0; i < updateIndex.length; i++) {
					schooltimesettingMapper.deleteByPrimaryKey(Integer.parseInt(updateIndex[i]));
				}
			}else {
				if (timeList.length < updateIndex.length) {
					return -1;
				}else if (timeList.length == updateIndex.length) {
					for (int i = 0; i < updateIndex.length; i++) {
						//删除考勤
						if (StringUtil.isBlank(timeList[i]) || timeList[i].indexOf("-") < 0) {
							schooltimesettingMapper.deleteByPrimaryKey(Integer.parseInt(updateIndex[i]));
							continue;
						}

						//修改考勤
						String timeTemp = timeList[i];
						String[] timeValue = timeTemp.split("-");
						Schooltimesetting time = new Schooltimesetting();
						time.setSchoolid(schoolVO.getId());
						time.setStarttime(DateUtil.formatStringToTime(timeValue[0], ""));
						time.setEndtime(DateUtil.formatStringToTime(timeValue[1], ""));
						time.setIndexnum(i + 1);
						time.setSellerid(1);
						time.setType((byte) 1);
						time.setId(Integer.parseInt(updateIndex[i]));
						schooltimesettingMapper.updateByPrimaryKeySelective(time);
					}
				}else {
					for (int i = 0; i < timeList.length; i++) {
						String timeTemp = timeList[i];
						if (StringUtil.isBlank(timeTemp) || timeTemp.indexOf("-") < 0)
							continue;
						String[] timeValue = timeTemp.split("-");
						Schooltimesetting time = new Schooltimesetting();
						time.setSchoolid(schoolVO.getId());
						time.setStarttime(DateUtil.formatStringToTime(timeValue[0], ""));
						time.setEndtime(DateUtil.formatStringToTime(timeValue[1], ""));
						time.setIndexnum(i + 1);
						time.setSellerid(1);
						time.setType((byte) 1);
						boolean flag = false;
						for (int j = 0; j < updateIndex.length; j++) {
							if (i == j) {
								time.setId(Integer.parseInt(updateIndex[j]));
								schooltimesettingMapper.updateByPrimaryKeySelective(time);
								flag = true;
								break;
							}
						}
						if (flag) {
							continue;
						}
						schooldao.addSchooltimesetting(time);
					}
				}
			}
		}else {
			if (timeList != null) {
				for (int i = 0; i < timeList.length; i++) {
					String timeTemp = timeList[i];
					if (StringUtil.isBlank(timeTemp) || timeTemp.indexOf("-") < 0)
						continue;
					String[] timeValue = timeTemp.split("-");
					Schooltimesetting time = new Schooltimesetting();
					time.setSchoolid(schoolVO.getId());
					time.setStarttime(DateUtil.formatStringToTime(timeValue[0], ""));
					time.setEndtime(DateUtil.formatStringToTime(timeValue[1], ""));
					time.setIndexnum(i + 1);
					time.setSellerid(1);
					time.setType((byte) 1);
					schooldao.addSchooltimesetting(time);
				}
			}
		}
		return 1;
	}
	/**
	 * <p>Title: updateSchoolDiscount</p>
	 * <p> 功能描述:修改促销 </p>
	 * @param schoolVO
	 * @return
	 */
	@Override
	public int updateSchoolDiscount(SchoolVO schoolVO) {
		//查询促销是否存在
		SchoolDiscountDO schoolDiscountDO = schooldao.querySchoolDiscount(schoolVO.getId());
		Map<String,Object> map = new HashMap<>();
		map.put("devicetype", schoolVO.getDevicetype());
		map.put("discountprice", schoolVO.getPrice());
		map.put("starttime", schoolVO.getStarttime());
		map.put("endtime", schoolVO.getEndtime());
		map.put("schoolid", schoolVO.getId());
		if (schoolDiscountDO != null) {
			if (schoolVO.getPrice() == null && StringUtil.isEmpty(schoolVO.getStarttime()) && StringUtil.isEmpty(schoolVO.getEndtime())) {
				schooldao.deleteSchoolDiscount(schoolVO.getId());
			}else {
				if (StringUtil.isEmpty(schoolVO.getStarttime()) || StringUtil.isEmpty(schoolVO.getEndtime())) {
					return -1;
				}
				int checkTime = DateUtil.formatStringToTime(schoolVO.getStarttime(), "yyyy-MM-dd HH:mm:ss")
						.compareTo(DateUtil.formatStringToTime(schoolVO.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
				if (checkTime != -1) {
					return -2;
				}
				return schooldao.updateSchoolDiscount(map);
			}
		}else {
			if (schoolVO.getDevicetype() == null) {
				map.put("devicetype", 2);
			}
			if (schoolVO.getPrice() == null && StringUtil.isEmpty(schoolVO.getStarttime()) && StringUtil.isEmpty(schoolVO.getEndtime())) {
				return 0;
			}else {
				if (StringUtil.isEmpty(schoolVO.getStarttime()) || StringUtil.isEmpty(schoolVO.getEndtime()) || schoolVO.getPrice() == null) {
					return -1;
				}else {
					int checkTime = DateUtil.formatStringToTime(schoolVO.getStarttime(), "yyyy-MM-dd HH:mm:ss")
							.compareTo(DateUtil.formatStringToTime(schoolVO.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
					if (checkTime != -1) {
						return -2;
					}
					schooldao.addSchoolDiscount(map);
				}
			}
		}
		return 0;
	}

	// 删除学校
	@Override
	@Transactional
	public int delSchool(int id) {
		int result = schooldao.deleteSchool(id);
		// 然后删除旧的考勤配置
		if (result > 0) {
			schooldao.deleteSchooltimesetting(id);
			//删除促销
			schooldao.deleteSchoolDiscount(id);
			//删除账户地区权限
			authUserDataDao.deleteBySchoolId(id);
		}
		return result;
	}
	/**
	 * <p>Title: querySchoolRegion</p>
	 * <p> 功能描述:查询指定学校的省市区 </p>
	 * @param paramForm
	 * @return
	 */
	@Override
	public List<RegionInfo> querySchoolRegion(ParamForm paramForm) {
		List<RegionInfo> regionList = new LinkedList<>();
		if (StringUtil.isNotEmpty(paramForm.getDis())) {
			 queryByDis(Integer.parseInt(paramForm.getDis()),regionList);
		}
		return regionList;
	}
	
	public void queryByDis(Integer dis,List<RegionInfo> regionList) {
		/*RegionInfo regionInfo = new RegionInfo();
		regionInfo.setRegionid(dis);
		List<RegionInfo> list = schooldao.queryRegion(regionInfo);
		if (list.size() > 0) {
			regionList.add(list.get(0));
			if (list.get(0).getParentid() > 1) {
				queryByDis(list.get(0).getParentid(),regionList);
			}
		}*/
	}

	@Override
	public SchoolDiscountVO querySchoolDiscount(Integer schoolid) {
		return SchoolDiscountDoToVO(schooldao.querySchoolDiscount(schoolid));
	}
	
	public SchoolDiscountVO SchoolDiscountDoToVO(SchoolDiscountDO schoolDiscountDO) {
		SchoolDiscountVO schoolDiscountVO = new SchoolDiscountVO();
		if (schoolDiscountDO != null) {
			schoolDiscountVO.setId(schoolDiscountDO.getId());
			schoolDiscountVO.setSchoolid(schoolDiscountDO.getSchoolid());
			schoolDiscountVO.setEndtime(DateUtil.formatDateToString(schoolDiscountDO.getEndtime(), null));
			schoolDiscountVO.setPrice(schoolDiscountDO.getDiscountprice());
			schoolDiscountVO.setStarttime(DateUtil.formatDateToString(schoolDiscountDO.getStarttime(), null));
		}
		return schoolDiscountVO;
	}
	
	/**
	 * <p>Title: synSchoolWithJxt</p>
	 * <p> 功能描述: 将家校通创建的学校同步到syn_orgnization表中和schoolinfoes表中的jxt_id字段</p>
	 * @param schoolVO
	 * @return
	 */
	private JSONObject synSchoolWithJxt(SchoolVO schoolVO) {
		if(schoolVO == null || StringUtils.isBlank(schoolVO.getSchoolname())) {
			throw new OpServiceException("学校名称为空");
		}
		JSONObject school = jxtService.getSchool(schoolVO.getSchoolname());
		if(school == null) {
			throw new OpServiceException("请先在家校通创建学校");
		}else {
			// 新增到syn_orgnization表
			sysOrgnizationService.insert(school.getString("uuid"), school.getString("schoolname"), "学校", school.getString("pUuid"));
			return school;
		}
	}
}
